import {
    getparamtersettings,
    postSethospitalparamtersettings,
    postSetuserparamtersettings,
    getItemList,
    getDepAreaList,
    getListByAreaName
} from '@/api/api'
import defaultSettings from '@/settings'
import { setAppConfig, getAppConfig } from '../../utils/auth'
import user from './user'
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage'
const { showSettings, fixedHeader, sidebarLogo } = defaultSettings
const appConfig = getAppConfig()

const state = {
  setTimeTip: `更改时令需谨慎! 因更改时令可能会导致班次或排队号发生变化，需实施根据医院实际号源情况而做判断是否可以更改时令。注：若更改时令后，会导致班次或排队号发生变化的，需去该机房重新发布一下号源！`,
  isShowEditScedule: false,
  showSettings: showSettings,
  fixedHeader: fixedHeader,
  sidebarLogo: sidebarLogo,
  clinicalContent : undefined ,
  paramConfig: {},
  appConfig: appConfig ? JSON.parse(appConfig) : {},
  roomIsUseSelectOption: false || localStorage.getItem('yjyy-roomIsUseSelect') == 1 ? true : false,
  gradeList: [], // 优先级
  privacyLevelList: [], // 保密等级
  appointTypeOptions: window.g.APPOINT_TYPE_OPTIONS || [], // 预约来源
  hisTypeOptions: [],
  departmentOptions: [], // 申请科室列表
  medcineOptions: ['上午班', '下午班'], // 检查班次
  doctorListOptions: [], // 申请医生
  areaNameOptions: [], // 院区
  depAreaOptions: [] , // 影像区域
  areaNameOptions: [], // 院区
  transportTypeOptions: [], // 转运方式
  transportToolsOptions: [], // 转运工具
  hisTypeOptions: [], // his类型
  wardNoOptions: [], // 病区数组
  materialOptions: [], // 药物
  gastroscopicMedicineOptions: [], // 胃镜药物
  currentRow: null,
}

const mutations = {
  SET_wardNoOptions: (state, value) => {
    state.wardNoOptions = value
  },
  SET_areaNameOptions: (state, value) => {
    state.areaNameOptions = value
  },
  SET_depAreaOptions: (state, value) => {
    state.depAreaOptions = value
    console.log('state.depAreaOptions', state.depAreaOptions)
  },
  SET_doctorListOptions: (state, value) => {
    state.doctorListOptions = value
  },
  SET_medcineOptions: (state, value) => {
    state.medcineOptions = value
  },
  SET_transportTypeOptions: (state, value) => {
    state.transportTypeOptions = value
  },
  SET_transportToolsOptions: (state, value) => {
    state.transportToolsOptions = value
  },
  SET_hisTypeOptions: (state, value) => {
    state.hisTypeOptions = value
  },
  SET_departmentOptions: (state, value) => {
    state.departmentOptions = value
  },
  SET_appointTypeOptions: (state, value) => {
    state.appointTypeOptions = value
  },
  SET_hisTypeOptions: (state, value) => {
    state.hisTypeOptions = value
  },
  SET_privacyLevelList: (state, value) => {
    state.privacyLevelList = value
  },
  SET_gradeList: (state, value) => {
    state.gradeList = value
  },
  SET_currentRow: (state, value) => {
    state.currentRow = value
  },
  SET_materialOptions: (state, value) => {
    state.materialOptions = value
  },
  SET_gastroscopicMedicineOptions: (state, value) => {
    state.gastroscopicMedicineOptions = value
  },
  SET_roomIsUseSelectOption: (state, value) => {
    state.roomIsUseSelectOption = value
  },
  Tigger_ISSHOWEDITScedule: (state, value) => {
    state.isShowEditScedule = value
  },
  CHANGE_SETTING: (state, { key, value }) => {
      if (state.hasOwnProperty(key)) {
          state[key] = value
      }
  },
  CONFIG_APP_SETTING(state, info) {
      state.appConfig = info
  },
  CONFIG_CLINICALCONTENT_SETTING(state, info) {
      let info1 = JSON.parse(info) || {}
      state.paramConfig = info1
      state.clinicalContent = info1.clinicalContent ? JSON.parse(info1.clinicalContent) : {}
  }
}

const handleItemListApi = async (params) => {
  const res = await getItemList(params)
  // console.log('==###==getItemList——res==###==', res)
  let list = []
  if (res.code === 10000) {
    list = res.content.list || []
  }
  return list
}

const getDepAreaListApi = async (params) => {
  const res = await getDepAreaList(params)
  // console.log('==###==getDepAreaList——res==###==', res)
  let list = []
  if (res.code === 10000) {
    list = res.content.list || []
  }
  return list
}

const getAreaNameListApi = async (params) => {
  const res = await getListByAreaName(params)
  let list = []
  if (res.code === 10000) {
    list = res.content.list || []
  }
  return list
}
// getInpatientWard() {
//   // 病区
//   let data = {
//     HospitalCode: this.hospitalCode,
//     type: '申请病区'
//   }
//   getItemListFunc(data).then(res => {
//     this.inpatientWardOptions = res.map(_item => _item.item)
//     // this.groupOptions.wardNo = this.inpatientWardOptions
//   })
// },
const actions = {
  // 病区
  async set_wardNoOptions({ commit }, data) {
    let list = await handleItemListApi(data)
    console.log('病区list', list)
    commit('SET_wardNoOptions', list)
  },
  // 院区
  async set_areaNameOptions({ commit }, data) {
    let list = await getAreaNameListApi(data)
    // console.log('院区list', list)
    commit('SET_areaNameOptions', list)
  },
  // 影像区域
  async set_depAreaOptions({ commit }, data) {
    let list = await getDepAreaListApi(data)
    // console.log('影像区域list', list)
    commit('SET_depAreaOptions', list)
  },
  // 申请医生
  async set_doctorListOptions({ commit }, data) {
    let list = await handleItemListApi(data)
    // console.log('申请医生list', list)
    const ats = list.map(_item => _item.item)
    commit('SET_doctorListOptions', ats)
  },
  // 检查班次
  async set_medcineOptions({ commit }, data) {
    let list = await handleItemListApi(data)
    // console.log('班次list', list)
    const ats = list.map(_item => _item.item)
    commit('SET_medcineOptions', ats)
  },
  // 运送方式
  async set_transportTypeOptions({ commit }, data) {
    let list = await handleItemListApi(data)
    console.log('运送方式list', list)
    commit('SET_transportTypeOptions', list)
  },
  // 运送工具
  async set_transportToolsOptions({ commit }, data) {
    let list = await handleItemListApi(data)
    console.log('运送工具list', list)
    commit('SET_transportToolsOptions', list)
  },
  // his类型
  async set_hisTypeOptions({ commit }, data) {
    let list = await handleItemListApi(data)
    console.log('his类型list', list)
    commit('SET_hisTypeOptions', list)
  },
  // 申请科室
  async set_departmentOptions({ commit }, data) {
    let list = await handleItemListApi(data)
    // console.log('申请科室list', list)
    const ats = list.map(_item => _item.item)
    commit('SET_departmentOptions', ats)
  },
  // 预约来源
  async set_appointTypeOptions({ commit }, data) {
    if (window.g.APPOINT_TYPE_OPTIONS) return
    let list = await handleItemListApi(data)
    // console.log('list', list)
    const ats = list.map(_item => _item.item).filter(ap => ap)
    // console.log('ats', ats)
    // list.forEach((it) => {
    //   it.value = it.item
    //   it.label = it.item
    //   return it
    // })
    commit('SET_appointTypeOptions', ats)
  },
  async set_appointTypeOptionsOnly({ commit }, data) {
    commit('SET_appointTypeOptions', data)
  },
  // his类型
  async set_hisTypeOptions({ commit }, data) {
    let list = await handleItemListApi(data)
    // console.log('list', list)
    list.forEach((it) => {
      it.value = it.itemValue
      it.label = it.item
      return it
    })
    commit('SET_hisTypeOptions', list)
  },
  // 保密等级
  async set_privacyLevelList({ commit }, data) {
    let list = await handleItemListApi(data)
    // console.log('list', list)
    list.forEach((it) => {
      it.value = it.itemValue
      it.label = it.item
      return it
    })
    commit('SET_privacyLevelList', list)
  },
  // 优先级
  async set_gradeList({ commit }, data) {
    let list = await handleItemListApi(data)
    commit('SET_gradeList', list)
  },
  set_currentRow({ commit }, data) {
    commit('SET_currentRow', data)
  },
  set_roomIsUseSelectOption({ commit }, data) {
      commit('SET_roomIsUseSelectOption', data)
  },
  tigger_isShowEditScedule({ commit }, data) {
      commit('Tigger_ISSHOWEDITScedule', data)
  },
  changeSetting({ commit }, data) {
      commit('CHANGE_SETTING', data)
  },
  // 获取医院及用户配置
  async getAppConfigSetting({
      commit,
      dispatch
  }, data) {
      const params = {
          hospitalCode: data && data.hospitalCode ? data.hospitalCode : user.state.hospitalCode,
          userId: user.state.id
      }
    await getparamtersettings(params).then(res => {
          if (res && res.code === 10000) {
              let localData = null
              if (res.content.hospitalParameterContent) {
                  localData = res.content.hospitalParameterContent // 列表参数配置信息都在这个content.hospitalParameterContent里面
              }
              // 把医技这边的配置和临床的配置设置到state里
              // console.log('====55555')
              dispatch('setHospitalConfigSettingToLocal', JSON.stringify(res.content))
              // console.log('====555', localData)
              let localData2 = ''
              try{
                localData2 = JSON.parse(localData) || {}
              }catch(e){
                //TODO handle the exception
                console.warn('====localData2', e)
              }
                  // let localUserData = null
              if (res.content.userParameterContent) {
                 // console.log('====9999')
                  let userParameterContent = JSON.parse(res.content.userParameterContent)
                  // // console.log('userParameterContent===>', userParameterContent)
                  if (typeof userParameterContent.registerRoom != 'undefined' || userParameterContent.registerRoom != '') {
                      // localStorage.setItem('registerRoom', userParameterContent.registerRoom)
                  }
                  // console.log('====777777')
                  localData2.userParameterContent = JSON.parse(res.content.userParameterContent)
              } else {
                  // localStorage.setItem('registerRoom', '')
              }
              // console.log('====666')
              dispatch('setAppConfigSetting', JSON.stringify(localData2))
          }
      })
  },
  // 把医技这边的配置和临床的配置设置到state里
  setHospitalConfigSettingToLocal({
    commit
  },data) {
    try {
      // 把医技这边的配置和临床的配置设置到state里
      // info1 = data
      // state.paramConfig = info1
      // state.clinicalContent = info1.clinicalContent ? JSON.parse(info1.clinicalContent) : {}
      commit('CONFIG_CLINICALCONTENT_SETTING', data)
    } catch (err) {
      // // console.log('setting/setHospitalConfigSettingToLocal', err)
    }
  },
  // 设置配置
  setAppConfigSetting({
    commit
  }, data) {
    try {
      const info = JSON.parse(data)
      // 保存在state.appConfig里
      commit('CONFIG_APP_SETTING', info)
      // 加密后保存在localStorage->YJYY-APPSETTING里
      setAppConfig(data)
    } catch (err) {
      // // console.log('setting/setAppConfigSetting', err)
    }
  },
  // 设置医院配置
  setConfigSetting_hospital({
      commit
  }, data) {
    return new Promise(async(resolve, reject) => {
      /*// // console.log('data.parameterContent', data.parameterContent)
      const params = {
          hospitalCode: data.hospitalCode,
          parameterContent: data.parameterContent
      }*/
      await postSethospitalparamtersettings(data).then(res => {
        if (res && res.code === 10000) {
            // // console.log('设置医院配置成功')
        }
        resolve(res)
      })
      reject()
    })
  },
  // 设置用户配置
  setConfigSetting_user({
    commit
  }, data) {
    return new Promise(async(resolve, reject) => {
      const params = {
          hospitalCode: data.hospitalCode,
          userId: user.state.id,
          parameterContent: data.parameterContent
      }
      await postSetuserparamtersettings(params).then(res => {
          if (res && res.code === 10000) {
              // // console.log('设置用户配置成功')
          }
          resolve(res)
      })
      reject()
    })
  },
  // 药物
  async SET_materialOptions({ commit }, data) {
    let list = await handleItemListApi(data)
    // console.log('list', list)
    list.forEach((it) => {
      it.value = it.item
      it.label = it.item
      return it
    })
    commit('SET_materialOptions', list)
  },
  // 胃镜药物
  async SET_gastroscopicMedicineOptions({ commit }, data) {
    let list = await handleItemListApi(data)
    // console.log('list', list)
    list.forEach((it) => {
      it.value = it.item
      it.label = it.item
      return it
    })
    commit('SET_gastroscopicMedicineOptions', list)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
